import { defineStore } from 'pinia';
import router from '@/router';
import { getUserInfo, login,phoneLogin,loginLogoutRequest, getMenuList } from '@/api/auth';
import { storage } from '@/utils/storage';
import { useNavTabStore } from './navTab';

interface IUserState {
  token: string | null;
  userInfo: {
    employeeName: string;
    // role: string;
  };
  permissions: string|null; 
  isShowMsg: string|null;
  menu: string|null;
}

export const useUserStore = defineStore({
  id: 'user',
  state: (): IUserState => ({
    token: storage.get('token'),
    userInfo: storage.get('userInfo') || { employeeName: '' },
    permissions: storage.get('permissions'),
    isShowMsg: storage.get('isShowMsg'),
    menu: storage.get('menu')
  }),
  getters: {
    isLogin(state) {
      return Boolean(state.token);
    }
  },
  actions: {
    resetUser() {
      const navTabStore = useNavTabStore();
      storage.remove('userInfo');
      storage.remove('token');
      storage.remove('menu')
      navTabStore.reset();
      this.$reset();
    },
    setToken(token: string) {
      this.token = token;
      storage.set('token', token);
    },
    async setUserInfo(data:any) {
      // const { data } = await getUserInfo();
      // if (data?.permissions?.length) this.setPermissions(data.permissions);
      this.userInfo = data;
      storage.set('userInfo', data);

      
      const res = await getMenuList({});
      const menu = JSON.stringify(res.data)
      storage.set('menu', menu);
      // storage.set('permissions', JSON.stringify(['xxx:ddd']))
    },
    setPermissions(permissions: string[]) {
      // this.permissions = permissions;
    },
    // 密码登录
    async login(params: any) {
      const { data } = await login(params);
      this.setToken(data.token);
      router.push('/dashboard');
      await this.setUserInfo(data);
      ElNotification({
        title: '登录成功!',
        type: 'success',
        message: `欢迎回来，${this.userInfo.employeeName}`
      });
    },
    //手机验证码登录
    async phoneLogin(params: any) {
      const { data } = await phoneLogin(params);
      this.setToken(data.token);
      router.push('/dashboard');
      await this.setUserInfo(data);
      ElNotification({
        title: '登录成功!',
        type: 'success',
        message: `欢迎回来，${this.userInfo.employeeName}`
      });
    },
    logout() {
      ElMessageBox.confirm('您确定要退出登录吗？', '提示') 
        .then( async () => {
          const data:any = await loginLogoutRequest({adminId:this.userInfo?.id})
          // if (data.code ==2000) {
            console.log(data.code)
            ElMessage.success('成功退出')
            this.resetUser();
            router.push('/login');
          // }
        })
        .catch(() => { });
    },
    async toLogin () {
      const data:any = await loginLogoutRequest({adminId:this.userInfo?.id})
      if (data.code ==2000 ) {
        this.resetUser();
        router.push('/login');
      }
    }
  }
});
